﻿using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Jhong.FunMVC
{
    public class RouteBase
    {

        public string Name { get; private set; }

        private string _matchRule;

        public object Defaults { get; private set; }


        public RouteBase(string name, string url, object defaults)
        {
            this.Name = name;
            this._matchRule = this.CreatePattern(url);
            this.Defaults = defaults;
        }

        internal bool IsMatch(string requestURL)
        {
            return Regex.IsMatch(requestURL, this._matchRule, RegexOptions.IgnoreCase);
        }

        private string CreatePattern(string requestURL)
        {
            var groups = new List<string>();
            var parameters = requestURL.Split('/');
            foreach (var p in parameters)
            {
                if (string.IsNullOrWhiteSpace(p)) continue;
                if (p.StartsWith("{") && p.EndsWith("}")) groups.Add("[^/]*");
                else groups.Add(p);
            }
            return "^/" + string.Join(@"/", groups);
        }

        public Microsoft.Owin.QueryString TransformRouteParameter(IOwinRequest request)
        {
            var localPath = request.Uri.LocalPath;
            var sb = new StringBuilder();
            var offset = -1;
            var arr = localPath.TrimStart('/').Split('/');
            foreach (var p in this.Defaults.GetType().GetProperties())
            {
                offset++;
                if (p.PropertyType != typeof(UrlParameter)) continue;
                sb.Append(string.Format("&{0}={1}", p.Name, arr[offset]));
            }
            var queryStr = request.QueryString.HasValue ? request.QueryString.Value + sb.ToString() : sb.Length > 0 ? sb.Remove(0, 1).ToString() : string.Empty;
            return new Microsoft.Owin.QueryString(queryStr);
        }


    }
}
